<template>
    <nav-header :title="formName.length > 15? '表单内容':formName">
		<view v-if="formName.length > 15" class="text-lg font-bold text-color-theme mx-3 pt-4" v-text="formName"></view>
		<view class="pt-4">
			<form-content :fieldList="fieldList" :businessId="formBusinessId" :formCode="formCode" @updateList="(val)=>{fieldList = val}"/>
		</view>
		<view v-if="!formStatus || formStatus == 'draft'" class="fixed bottom-0 w-full flex bg-white z-20 py-3">
			<view class="mr-1 ml-4 py-3 text-center border w-1_2 bg-orange-400 text-white text-sm rounded" @click="formSubmit('approve')">提交审核</view>
			<view class="ml-1 mr-4 py-3 text-center border w-1_2 bg-theme text-white text-sm rounded" @click="formSubmit('draft')">保存草稿</view>
		</view>
		<u-toast ref="uToast"></u-toast>
    </nav-header>
</template>
<script>
import FormContent from '../content.vue'
import NavHeader from '@/components/nav_header.vue'
import * as uploadApi from '@/interface/common/upload.js'
import { getFormInfo, addLogmaster, updateLogmaster, getLogmasterInfo } from '@/interface/junchuang/form'
export default {
    name: 'FormDetail',
    components: { NavHeader,FormContent },
    data(){
        let fomView = this.$store.state.formView;
        return {
            isReadonly: true,
            formId: '',
            formCode: '',
            formBusinessId: '',
            fieldList: [],
            formName: '',
			formStatus: '',
            fomViewStore: fomView,
            formValues: {}
        }
    },
	onLoad(e) {
		this.formId = e.formId
		this.formCode = e.formCode
		this.formBusinessId = e.businessId || e.id || ''
	},
    mounted(){
        if (!(this.formId || this.formCode)){
            this.$u.toast('缺少表单编号');
            this.$util.goBack()
        }
        // await this.initFlow()
        if (this.formBusinessId){
            // 获取表单历史数据
            this.getFormValue();
        } else {
            this.isReadonly = false;
            // 获取表单对象
            this.getFormDef();
        }
    },
    methods:{
        getFormDef(){
            let code = this.formId || this.formCode
            getFormInfo(code).then(res=>{
                this.formId = res.data.id
                if(res.success){
                    this.fieldList = [];
                    const pushList=(source, target)=>{
                        const ignore = ["DatePickerMultiple", "TimePickerMultiple"];
                        for (const item of source) {
                            if (item.type == 'Layout' && item.config.row > 0) {
                                for (let y = 0; y < item.config.row; y++) {
                                    const row = item.config.colList[y];
                                    for (let x = 0; x < item.config.col; x++) {
                                        const col = row[x];
                                        pushList(col, target);                                      
                                    }                            
                                }
                                continue;
                            }
							item['readonly'] = false
                            let val = this.formValues[item.name]
                            if(val) {
                                const type = item.type;
                                if (type == 'TimePickerMultiple' || type == 'Checkbox' || type == 'DatePickerMultiple' || type == 'Switch'){
                                    val = JSON.parse(val);
                                } else if(type == 'Rate' || type == 'InputNumber'){
                                    if ((val+'').indexOf('.') == -1) val = parseInt(val);
                                    else val = parseFloat(val);
                                }
                                item.value = val;
                            }
							const macro = item.config.macro
							if (macro) {
							    if (macro.label == item.value) {
							        item.value = this.getMacroValue(macro.value)
							    }
							}
                            target.push(item);
                        }
                    }
                    try {
                        this.formName = res.data.name;
                        let tempList = JSON.parse(res.data.parsehtml);
                        pushList(tempList, this.fieldList);
                    } catch (error) {
                        console.error(error)
                        this.fieldList = [];
                    }
                }
            }).catch((msg)=>{
                this.$u.toast(msg)
            });
        },
        getFormValue(){
            getLogmasterInfo(this.formBusinessId).then(res=>{
                if (res.success) {
                    this.isReadonly = res.data.status == 'complete' || res.data.status == 'pass';
                    let values = {};
                    for (const it of res.data.values) {
                        values[it.fieldkey] = it.newvalue;
                    }
                    this.formValues = values;
					this.formStatus = res.data.status;
                    this.formId = res.data.formId
                    this.getFormDef();
                    return;
                }
                this.$u.toast('获取表单内容失败');
                this.$util.goBack()
            }).catch(()=>{
                this.$u.toast('获取表单内容失败');
                this.$util.goBack()
            });
        },
        formSubmit(status){
			const v = this
			v.$util.showModal('确认信息', '即将保存表单, 是否继续?', true, '保存', '取消', (res) => {
				v._saveForm(status)
			}, (res) => {
				return
			})
        },
        async _saveForm(status, callback){
            const values = [], v = this
            let title='',fileIdsList = []
            for(let field of this.fieldList){
                const isTitle = field.config.isTitle;
                const val = field.value;
                if (isTitle) {
                    title = val;
                }
				console.log(field);
                if (v.$util.isNotBlank(val)) {
                    if (field.config.make == 'Uploader') {
                        let fileIds = await uploadApi.startEasyUpload(field.value); 
						fileIds.split(',').forEach(fileId=>{
							fileIdsList.push(fileId + ',' + field.id)
						})
                    } 
                    if (field.config.make == 'field') {
                        let cell = {
                            fieldkey: field.name,
                            newvalue: val,
                            fieldlabel: field.label
                        }
                        values.push(cell);
                    }
                }
            }
            let form = {
                id: v.formBusinessId,
                formId: v.formId,
                name: title,
                fieldList: JSON.stringify(values),
                fileIdsList: fileIdsList,
				status: status
            }
            if (v.$util.isBlank(form.id)){
                addLogmaster(form).then(res=>{
                    v.formBusinessId = res.data.id
                    form.id = res.data.id
                    if (res.success){
                        v.fomViewStore.indexActive = 'history';
                        v.fomViewStore.historyActive = status;
                        if (typeof callback != 'undefined' && callback instanceof Function) {
                            callback(form)
                            return
                        }
						v.$refs.uToast.show({
							message: res.msg,
							complete() {
								v.$util.goBack()
							}
						})
                        return;
                    }
                    v.$u.toast(res.message);
                });
            } else {
                updateLogmaster(form).then(res=>{
                    if (res.success){
                        v.fomViewStore.indexActive = 'history';
                        v.fomViewStore.historyActive = status;
                        if (typeof callback != 'undefined' && callback instanceof Function) {
                            callback(form)
                            return
                        }
						v.$refs.uToast.show({
							message: res.msg,
							complete() {
								v.$util.goBack()
							}
						})
                        return;
                    }
                    v.$u.toast(res.message);
                });
            }
        },
		// 宏定义赋值
		getMacroValue(key){
		    const user = this.$store.getters.user
		    switch(key) {
		        case '{{##LoginName##}}':
		            return user.userName;
		        case '{{##CurrentDate##}}':
		            return this.$util.getFormatDate('')
		        case '{{##CurrentDateTime##}}':
		            return this.$util.getFormatDate('','yyyy-0m-0d 0h:0f')
		    }
		},
    }
}
</script>

